import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Notification } from '@arco-design/web-react';
import { ConversationInfoItem, ConversationInfoListItemType, ConversationType, PermissionType } from "../../types/conversation";
import { ConversationEditor } from "./components/ConversationEditor";
import { ConversationInfoList } from "./components/ConversationInfoList";
import E from "wangeditor";

import './index.css'
import { endTicket, getAllConversationInfosWithStaff, getConversationById, getConversationInfo, sendMessage } from "../../../api/conversation";
import { useRecoilValue } from "recoil";
import { userInfoState } from "../../../store/userInfo";
import { orderTicket } from "../../../api/ticket";
import { useStaffIm } from "../../../hooks/useStaffIm";
import { useManagerIm } from "../../../hooks/useManagerIm";

interface ConversationWindowsProps {
  currentConversation: ConversationInfoItem;
  initConversationInfo: (conversation?: ConversationInfoItem) => void;
}

export const ConversationWindows: React.FC<ConversationWindowsProps> = (props) => {
  const { currentConversation, initConversationInfo } = props;
  const socket = useStaffIm();
  const { user_info, another_user_info } = currentConversation;
  const conversationRef = useRef(currentConversation);
  const userInfo = useRecoilValue(userInfoState);

  const [conversationData, setConversationData] = useState<Array<ConversationInfoListItemType>>([]);

  const getData = useCallback(async (conversation: ConversationInfoItem) => {
    if (!conversation) return [];
    let result;
    if (userInfo.permission === 3) { // 如果是普通用户，会话窗只有一个，所以只需要获取所有会话内容即可
      result = await getAllConversationInfosWithStaff(userInfo.id);
    } else {
      result = await getConversationInfo(conversation.conversation_id);
    }
    setConversationData(result.data.data as any);
    return result;
  }, []);

  const handleSubmit = useCallback(async (curEditor: E) => {
    if (curEditor) {
      if (currentConversation.type === ConversationType.Serving) {

        socket.emit('server', {
          info: {
            send_user_id: userInfo.id,
            content: curEditor.txt.text(), // 内容
          },
          conversation: currentConversation,
        });

      } else {
        const conversation = await sendMessage({
          user_id: user_info.id, // 发起者
          another_user_id: another_user_info.id, // 接受者
          content: curEditor.txt.text(), // 内容
        });

        await initConversationInfo(conversation);

        await getData(currentConversation) // 重新拉取数据
      }
    }
  }, [currentConversation]);

  const handleSubmitImage = useCallback(async (_curEditor: E, url: string) => {
    if (currentConversation.type === ConversationType.Serving) {

      socket.emit('server', {
        info: {
          send_user_id: userInfo.id,
          content: url, // 内容
          content_type: 2,
        },
        conversation: currentConversation,
      });

    } else {
      const conversation = await sendMessage({
        user_id: user_info.id, // 发起者
        another_user_id: another_user_info.id, // 接受者
        content: url, // 内容
        content_type: 2,
      });

      await initConversationInfo(conversation);

      await getData(currentConversation) // 重新拉取数据
    }
  }, []);

  const handleEndTicket = useCallback(async () => {
    const result = await endTicket(currentConversation.conversation_id, userInfo.id);
    const { data } = result;
    const { conversation, code } = data;
    if (code === 200) {
      await initConversationInfo(conversation);
    }
  }, [currentConversation]);

  const handleOrderTicket = useCallback(async () => {
    const result = await orderTicket(userInfo.id, currentConversation.conversation_id);
    const { data } = result;
    const { conversation } = data;
    await initConversationInfo(conversation);
  }, [currentConversation]);

  const anotherInfo = useMemo(() => {
    if (userInfo.id === user_info.id) {
      return another_user_info;
    }
    return user_info;
  }, [currentConversation, userInfo]);

  const { username } = anotherInfo;

  useEffect(() => {
    getData(currentConversation);
    conversationRef.current = currentConversation;
  }, [currentConversation]);

  useEffect(() => {
    if (userInfo.id) {
      const { conversation_id } = conversationRef.current;
      if (conversation_id) {
        socket.on(`conversation_${conversation_id}`, async (data: any) => {
          if (!data.new_info) {
            if (data.type === ConversationType.End) {
              if (userInfo.permission === PermissionType.customer) {
                Notification.info({ title: '提示', content: '本次服务已经结束，请给出评价' });
                const defaultConversation = await getConversationById(0);
                await initConversationInfo(defaultConversation);
                socket.removeAllListeners(`conversation_${conversation_id}`);
                return;
              }
            }
            await initConversationInfo();
            socket.removeAllListeners(`conversation_${conversation_id}`);
            return;
          }
          if (data.new_info.conversation_id === conversationRef.current.conversation_id) {
            await initConversationInfo(conversationRef.current);
            getData(conversationRef.current);
          }
        });
      }
    }
  }, [userInfo, conversationRef.current.conversation_id]);

  return <div className="conversation-windows-wrapper">
    <div className="conversation-windows-header">
      {/* <img className="conversation-windows-header-img" src={header_img} alt="" /> */}
      <div className="conversation-windows-user-name">{anotherInfo.permission === PermissionType.staff ? '基础客服' : username}</div>
    </div>
    <div className="conversation-windows-content">
      <ConversationInfoList data={conversationData} />
      <ConversationEditor
        currentConversation={currentConversation}
        handleSubmitImage={handleSubmitImage}
        handleEndTicket={handleEndTicket}
        handleSubmit={handleSubmit}
        handleOrderTicket={handleOrderTicket} />
    </div>
  </div>
}
